﻿using Common.Log;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DryWCS.Service.DbContext
{
    public class LocalDbContext<T> where T : class, new()
    {
        public LocalDbContext()
        {
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                //ConnectionString = "server=Localhost;uid=root;pwd=!QAZ2wsx;database=HK_JST_WCS",
                ConnectionString = "server=Localhost;uid=sa;pwd=123456;database=HK_JST_WCS",
                //ConnectionString = ConfigurationManager.ConnectionStrings["DBCStr"].ConnectionString,
                DbType = DbType.SqlServer,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
                IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
            });

            //调式代码 用来打印SQL 
            Db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql + "\r\n" +
                    Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };

            //表不存在创建表
            Type t = typeof(T);
            object[] objAttrs = t.GetCustomAttributes(typeof(SugarTable), true);
            SugarTable sb = objAttrs[0] as SugarTable;
            if (!string.IsNullOrEmpty(sb.TableName))
            {
                if (!Db.DbMaintenance.IsAnyTable(sb.TableName))
                    DbFirst();
            }
        }

        //注意：不能写成静态的
        public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作
        //public SimpleClient<Student> StudentDb { get { return new SimpleClient<Student>(Db); } }//用来处理Student表的常用操作
        //public SimpleClient<School> SchoolDb { get { return new SimpleClient<School>(Db); } }//用来处理School表的常用操作
        public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } }//用来处理T表的常用操作



        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public virtual List<T> GetList()
        {
            return CurrentDb.GetList();
        }

        /// <summary>
        /// 根据ID获取一条
        /// </summary>
        /// <returns></returns>
        public virtual T GetById(decimal id)
        {
            return CurrentDb.GetById(id);
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool DeleteByPK(dynamic id)
        {
            return CurrentDb.DeleteById(id);

        }

        /// <summary>
        /// 根据实体删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(T obj)
        {
            return CurrentDb.Delete(obj);
        }

        public virtual int Delete(List<T> obj)
        {
            return Db.Deleteable(obj).ExecuteCommand();
        }


        /// <summary>
        /// 根据实体更新
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual bool Update(T obj)
        {
            return CurrentDb.Update(obj);
        }

        /// <summary>
        /// 根据实体更新
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual int Update(List<T> obj)
        {
            return Db.Updateable(obj).ExecuteCommand();
        }

        /// <summary>
        /// 根据实体插入
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual bool Insert(T obj)
        {
            if (obj == null)
            {
                return false;
            }
            return CurrentDb.Insert(obj);
        }

        /// <summary>
        /// 根据实体List 批量插入
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public virtual int InsertTable(List<T> objList)
        {
            if (objList == null || objList.Count <= 0)
            {
                return -1;
            }
            return Db.Insertable(objList.ToArray()).ExecuteCommand();
        }



        /// <summary>
        /// 模糊匹配查询
        /// </summary>
        /// <returns></returns>
        //public virtual List<T> GetModelsByLike()
        //{
        //    T t = new T();
        //    Type type = t.GetType();
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append($"SELECT * FROM {type.Name.Replace("Model","")} WHERE 1=1 AND ");
        //    foreach (PropertyInfo p in type.GetProperties())
        //    {
        //        switch (p.PropertyType.ToString().ToLower())
        //        {
        //            case "system.string":
        //                sb.Append("");
        //                break;
        //            case "system.datetime":
        //                p.SetValue(t, Convert.ToDateTime(item.InnerText));
        //                break;
        //            case "system.int":
        //                p.SetValue(t, Convert.ToInt32(item.InnerText));
        //                break;
        //            case "system.decimal":
        //                p.SetValue(t, Convert.ToDecimal(item.InnerText));
        //                break;
        //            case "system.double":
        //                p.SetValue(t, Convert.ToDouble(item.InnerText));
        //                break;
        //            case "system.bool":
        //                p.SetValue(t, Convert.ToBoolean(item.InnerText));
        //                break;
        //        }
        //    }
        //    return Db.Ado.SqlQuery(sb.ToString()).t;
        //}
        /// <summary>
        /// 创建表
        /// </summary>


        public virtual void DbFirst()
        {
            Db.CodeFirst.BackupTable().InitTables(typeof(T));
        }

        /// <summary>
        /// 备份数据库
        /// </summary>
        /// <param name="path">备份路径</param>
        /// <returns></returns>
        public virtual int BackUp(string path)
        {
            try
            {

                string sql = $" BACKUP DATABASE HK_JST_CCCS to DISK = '{path}\\HK_JST_CCCS.bak' ";
                return Db.Ado.ExecuteCommand(sql);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("数据库操作异常。", ex);
                return 0;
                throw (ex);
            }
        }


        /// <summary>
        /// 还原数据库
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="name">数据库名称</param>
        /// <returns></returns>
        public virtual int Reduction(string path)
        {

            try
            {
                string sql = $"USE master RESTORE DATABASE HK_JST_CCCS FROM DISK = '{path}'  WITH STATS = 10,Replace;";
                //string cmdText = $" restore database HK_JST_CCCS from disk = '{path}' ";

                //string setOffline = " Alter database HK_JST_CCCS Set Offline With rollback immediate ";
                //string setOnline = " Alter database HK_JST_CCCS Set Online With Rollback immediate ";
                //string sql = $"{setOffline}{cmdText}{setOnline} ";
                return Db.Ado.ExecuteCommand(sql);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("数据库操作异常。", ex);
                return 0;
                throw (ex);
            }
        }

    }
}
